﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.Core.BLL
{
    public class CategoryListView
    {
        public string TitleNone { get; set; }
        public int CatIndex { get; set; }
        public int CatId { get; set; }
        public string Title { get; set; }
        public int SubCat { get; set; }
        public int SubCatx { get; set; }
        public string Description { get; set; }
        public int SiteId { get; set; }
    }

    public class Categories
    {
        public static Categories Instance
        {
            get { return new Categories(); }
        }

        public static CategoryListView LoadDataFromListItem(ArticleCategory item)
        {
            var objCategory = new CategoryListView
                                  {
                                      CatId = item.CatID,
                                      CatIndex = Convert.ToInt32(item.CatIndex),
                                      Description = item.Description,
                                      SubCat = Convert.ToInt32(item.SubCat),
                                      SubCatx = Convert.ToInt32(item.SubCatx),
                                      Title = item.Title,
                                      TitleNone = item.TitleNone,
                                      SiteId = item.SiteID
                                  };
            return objCategory;
        }

        /// <summary>
        /// Create Category
        /// </summary>
        /// <param name="title">Title Category</param>
        /// <param name="description">Category Description</param>
        /// <param name="titleNone">Title Category Non Utf-8</param>
        /// <param name="catIndex">Category Index</param>
        /// <param name="subCat">Sub Category</param>
        /// <param name="subCatx">Sub Sub Category</param>
        /// <param name="siteId">Site Id</param>
        /// <returns></returns>
        public bool Create(string title, string description, string titleNone, int catIndex, int subCat, int subCatx, int siteId)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    var objCategory = new ArticleCategory
                                          {
                                              CatIndex = catIndex,
                                              Description = Common.Instance.Truncate(description, 300, false, false),
                                              SubCat = subCat,
                                              SubCatx = subCatx,
                                              Title = Common.Instance.Truncate(title, 250, false, false),
                                              TitleNone = Common.Instance.Truncate(titleNone, 250, false, false),
                                              SiteID = siteId
                                          };

                    dc.ArticleCategories.InsertOnSubmit(objCategory);
                    dc.SubmitChanges();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Update Category
        /// </summary>
        /// <param name="catId">Category Id</param>
        /// <param name="title">Category Title</param>
        /// <param name="description">Category Description</param>
        /// <param name="titleNone">Title Category Non Utf-8</param>
        /// <param name="catIndex">Category Index</param>
        /// <param name="subCat">Sub Category</param>
        /// <param name="subCatx">Sub Sub Category</param>
        /// <param name="siteId">Site Id</param>
        /// <returns></returns>
        public bool Update(int catId, string title, string description, string titleNone, int catIndex, int subCat, int subCatx, int siteId)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    var objCategory = (dc.ArticleCategories.Where(p => p.CatID == catId)).Single();
                    objCategory.Title = Common.Instance.Truncate(title, 250, false, false);
                    objCategory.TitleNone = Common.Instance.Truncate(titleNone, 250, false, false);
                    objCategory.Description = Common.Instance.Truncate(description, 300, false, false);
                    objCategory.CatIndex = catIndex;
                    objCategory.SubCat = subCat;
                    objCategory.SubCatx = subCatx;
                    objCategory.SiteID = siteId;

                    dc.SubmitChanges();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Delete Cateogory
        /// </summary>
        /// <param name="catId">Category Id</param>
        /// <param name="siteId">Site Id</param>
        /// <returns></returns>
        public bool Delete(int catId, int siteId)
        {
            try
            {
                using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
                {
                    dc.Justin_ArticleCategory_Delete(catId, siteId);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Get Parent Category
        /// </summary>
        /// <param name="subCat">Sub Category</param>
        /// <param name="subCatx">Sub Sub Category</param>
        /// <param name="siteId">Site Id</param>
        /// <returns></returns>
        public List<CategoryListView> GetParentCat(int subCat, int subCatx)
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var query = from articleCategory in dc.ArticleCategories
                            where
                                (Configs.SiteId == -1 || articleCategory.SiteID == Configs.SiteId)
                                && articleCategory.SubCat == subCat
                                && articleCategory.SubCatx == subCatx
                            orderby articleCategory.CatIndex ascending
                            select new CategoryListView
                                       {
                                           CatId = articleCategory.CatID,
                                           CatIndex = Convert.ToInt32(articleCategory.CatIndex),
                                           Description = articleCategory.Description,
                                           SiteId = articleCategory.SiteID,
                                           SubCat = Convert.ToInt32(articleCategory.SubCat),
                                           SubCatx = Convert.ToInt32(articleCategory.SubCatx),
                                           Title = articleCategory.Title,
                                           TitleNone = articleCategory.TitleNone
                                       };

                return query.ToList();
            }
        }

        /// <summary>
        /// Get Category
        /// </summary>
        /// <param name="catId">Category Id</param>
        /// <returns></returns>
        public CategoryListView GetById(int catId)
        {
            using (var dc = new EmptyWallGalleryDataContext(Configs.ConnectionString))
            {
                var query = (from articleCategory in dc.ArticleCategories
                             where articleCategory.CatID == catId
                             select articleCategory).SingleOrDefault();

                return LoadDataFromListItem(query);
            }
        }

        /// <summary>
        /// Write Category Menu
        /// </summary>
        /// <param name="siteId">Site Id</param>
        /// <param name="writeFile">Is Write File</param>
        /// <returns></returns>
        public string WriteCategory(bool writeFile)
        {
            var strCount = new StringBuilder();
            var strWrite = new StringBuilder();
            try
            {
                var reader = GetParentCat(0, 0);
                strWrite.Append("<ul class=\"topnav\">");
                strWrite.Append("   <li class=\"first\">");
                strWrite.Append("       <a id=\"mnu_item_0\" href=\"").Append(Configs.HomeUrl).Append("\" title=\"Home\"><span></span></a>");
                strWrite.Append("   </li>");
                strCount.Append("0,");

                foreach (var categoryListView in reader.Where(categoryListView => categoryListView.CatId != 1))
                {
                    var catPath = Configs.HomeUrl + "c" + categoryListView.CatId + "s" + categoryListView.SubCat + "x" +
                                  categoryListView.SubCatx + "/" + categoryListView.TitleNone + ".aspx";
                    var reader2 = GetParentCat(categoryListView.CatId, 0);

                    strWrite.Append("   <li>");
                    strWrite.Append("       <a title=\"").Append(
                        HttpContext.Current.Server.HtmlEncode(categoryListView.Title)).Append("\" id=\"mnu_item_").
                        Append(categoryListView.CatId).Append("\" href=\"").Append(reader2.Count > 0 &&
                                                                                   categoryListView.CatId != 25
                                                                                       ? Configs.HomeUrl + "c" + reader2[0].CatId + "s" + reader2[0].SubCat + "x" + reader2[0].SubCatx + "/" + reader2[0].TitleNone + ".aspx"
                                                                                       : catPath).Append
                        ("\">").Append(
                            HttpContext.Current.Server.HtmlEncode(categoryListView.Title)).Append("</a>");
                    
                    strCount.Append(categoryListView.CatId).Append(",");

                    if (reader2.Count > 0 && categoryListView.CatId != 25)
                    {
                        strWrite.Append("       <ul class=\"subnav\">");
                        foreach (var listView in reader2)
                        {
                            var catPath2 = Configs.HomeUrl + "c" + listView.CatId + "s" + listView.SubCat + "x" +
                                  listView.SubCatx + "/" + listView.TitleNone + ".aspx";
                            var reader3 = GetParentCat(listView.SubCat, listView.CatId);

                            strWrite.Append("           <li>");
                            strWrite.Append("               <a title=\"").Append(
                                HttpContext.Current.Server.HtmlEncode(listView.Title)).Append("\" href=\"").Append(
                                    reader3.Count > 0 ? "#" : catPath2).Append("\">").Append(
                                        HttpContext.Current.Server.HtmlEncode(listView.Title)).Append("</a>");

                            if (reader3.Count > 0)
                            {
                                strWrite.Append("           <ul>");
                                foreach (var view in reader3)
                                {
                                    strWrite.Append("               <li>");
                                    strWrite.Append("                   <a title=\"").Append(
                                        HttpContext.Current.Server.HtmlEncode(view.Title)).Append("\" href=\"/c").Append(
                                            view.CatId).Append("s").Append(view.SubCat).Append("x").Append(view.SubCatx)
                                        .Append("/").Append(view.TitleNone).Append("\">").Append(
                                            HttpContext.Current.Server.HtmlEncode(view.Title)).Append("</a>");
                                    strWrite.Append("               </li>");
                                }
                                strWrite.Append("           </ul>");
                            }
                            strWrite.Append("           </li>");
                        }
                        strWrite.Append("       </ul>");
                    }
                    strWrite.Append("   </li>");
                }

                //strWrite.Append("   <li>");
                //strWrite.Append("       <a id=\"mnu_item_9999\" href=\"/Home/Contact\" title=\"Liên hệ\">Liên hệ</a>");
                //strWrite.Append("       <ul>");
                //strWrite.Append("           <li><a href=\"/Home/Contact\" title=\"Thông tin liên hệ\">Thông tin liên hệ</a></li>");
                //strWrite.Append("           <li><a href=\"/Home/Feedback\" title=\"Ý kiến phản hồi\">Ý kiến phản hồi</a></li>");
                //strWrite.Append("       </ul>");
                //strWrite.Append("   </li>");
                //strWrite.Append("   <li>");
                //strWrite.Append("       <div class=\"boxSearch\">");
                //strWrite.Append("           <input type=\"text\" name=\"txtSearch\" id=\"txtSearch\" onkeypress=\"return ShowSearch(event);\" value=\"tìm kiếm...\" onfocus=\"javascript:ChangeStatus(this,1,'tìm kiếm...');\" onblur=\"javascript:ChangeStatus(this,0,'tìm kiếm...');\" />");
                //strWrite.Append("           <input type=\"button\" name=\"btnSearch\" id=\"btnSearch\" value=\"\" />");
                //strWrite.Append("       </div>");
                //strWrite.Append("   </li>");
                strWrite.Append("</ul>");
                strWrite.Append("<script language=\"javascript\" type=\"text/javascript\">var MenuItem=[").Append(
                    strCount.ToString().Substring(0, strCount.ToString().Length - 1)).Append("];</script>");

                if (writeFile)
                {
                    using (var writer = new StreamWriter(Configs.FolderSaveData + "0afa541d68697b0b25e9b740ee9dab80_cat.htm", false, Encoding.UTF8))
                    {
                        writer.Write(strWrite);
                        writer.Flush();
                        writer.Close();
                    }
                    return "Done";
                }
                return strWrite.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// Write Category BackEnd
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="notIn">Not In</param>
        /// <param name="selectedId">Selected Id</param>
        /// <returns></returns>
        public string WriteCategoryInside(int type, int notIn = 0, string selectedId = "")
        {
            var strWrite = new StringBuilder();

            switch (type)
            {
                case 1:
                    strWrite.Append("<table border=\"0\" class=\"tblMain\" width=\"100%\">");
                    strWrite.Append("<tr class=\"header\">");
                    strWrite.Append("<th align=\"center\"><input type=\"checkbox\" name=\"cboCheck\" id=\"check_all\" /></th>");
                    strWrite.Append("<th>Tên danh mục</th>");
                    strWrite.Append("<th>Mô tả</th>");
                    strWrite.Append("<th align=\"center\">Hiển thị trên menu</th>");
                    strWrite.Append("</tr>");
                    break;
                case 2:
                    strWrite.Append("<select name=\"cboCategory\" class=\"cboCategory\">");
                    strWrite.Append("<option value=\"0,0\">None</option>");
                    break;
                case 3:
                    strWrite.Append("<div class=\"divCategory\">");
                    break;
                case 4:
                    strWrite.Append("<select name=\"cboCategory\">");
                    strWrite.Append("<option value=\"0\">View all categories</option>");
                    break;
                case 5:
                    strWrite.Append("<select name=\"c\">");
                    strWrite.Append("<option value=\"0\">Toàn bộ các mục</option>");
                    break;
            }

            var reader = GetParentCat(0, 0);

            foreach (var categoryListView in reader)
            {
                string strAction;
                switch (type)
                {
                    case 1:
                        {
                            //strWrite.Append(i % 2 == 0 ? "<tr style=\"background-color:#F9F9F9;\">" : "<tr>");
                            strWrite.Append("<tr>");

                            string strLinkEdit;
                            if (categoryListView.CatId != 1 && categoryListView.CatId != 10 && categoryListView.CatId != 11)
                            {
                                strLinkEdit = "<a class=\"lnkArticle\" href=\"?action=Edit&CatID=" + categoryListView.CatId + "\" title=\"" + categoryListView.Title + "\">" + categoryListView.Title + "</a>";
                                strAction = "<span class=\"edit\"><a href=\"?action=Edit&CatID=" + categoryListView.CatId + "\">Sửa</a> | </span>";
                                //strAction += "<span class=\"delete\"><a onclick=\"javascript:return confirm('Are you sure ?!')\" href=\"?action=Delete&CatID=" + categoryListView.CatId + "\">Xóa</a></span>";
                                strWrite.Append("<td align=\"center\"><input type=\"checkbox\" class=\"checkbox\" name=\"cboCheck\" value=\"").Append(categoryListView.CatId).Append("\" /></td>");
                            }
                            else
                            {
                                strLinkEdit = "<a class=\"lnkArticle\" href=\"#\" title=\"" + categoryListView.Title + "\">" + categoryListView.Title + "</a>";
                                strAction = "";
                                strWrite.Append("<td align=\"center\"></td>");
                            }
                            strWrite.Append("<td onmouseover=\"javascript:Util.DisplayAction(").Append(categoryListView.CatId).Append(");\" onmouseout=\"javascript:Util.HideAction(").Append(categoryListView.CatId).Append(");\">").Append(strLinkEdit).Append("<div style=\"display:none;\" class=\"row-actions\" id=\"row-actions-").Append(categoryListView.CatId).Append("\">").Append(strAction).Append("</div></td>");
                            strWrite.Append("<td>").Append(categoryListView.Description).Append("</td>");
                            strWrite.Append("<td align=\"center\">").Append((categoryListView.SiteId == 1 ? "Có" : "Không")).Append("</td>");  //reader["TotalArticles"].ToString()).Append("</td>");
                            strWrite.Append("</tr>");
                        }
                        break;
                    default:
                        if (type == 2 | type == 4 | type == 5)
                        {
                            if (categoryListView.CatId != notIn)
                            {
                                if (selectedId == Convert.ToString(categoryListView.CatId))
                                {
                                    strWrite.Append("<option selected=\"selected\" value=\"").Append(
                                        categoryListView.CatId).Append(",").Append(categoryListView.SubCat).Append(",").
                                        Append(categoryListView.SubCatx).Append("\">")
                                        .Append(categoryListView.Title).Append("</option>");
                                }
                                else if (categoryListView.CatId != 1)
                                {
                                    strWrite.Append("<option value=\"").Append(categoryListView.CatId).Append(",").
                                        Append(categoryListView.SubCat).Append(",").Append(categoryListView.SubCatx).
                                        Append("\">").Append(categoryListView.Title).Append("</option>");
                                }
                            }
                        }
                        else if (type == 3 && categoryListView.CatId != 1 && categoryListView.CatId != 10 && categoryListView.CatId != 11)
                        {
                            strWrite.Append(
                                "<span class=\"cboCatItem\"><label><input type=\"checkbox\" id=\"cboCategory").Append(
                                    categoryListView.CatId).Append("\" name=\"cboCategory\" value=\"").Append(
                                        categoryListView.CatId).Append("|").Append(categoryListView.SubCat).Append("|").
                                Append(categoryListView.SubCatx).Append("\" />").Append(categoryListView.Title).Append(
                                    "</label></span>");
                        }
                        break;
                }

                var reader2 = GetParentCat(categoryListView.CatId, 0);

                foreach (var listView in reader2)
                {
                    switch (type)
                    {
                        case 1:
                            //strWrite.Append(i % 2 == 0 ? "<tr style=\"background-color:#F9F9F9;\">" : "<tr>");
                            strWrite.Append("<tr>");

                            if (listView.CatId != 1 && listView.CatId != 10 && listView.CatId != 11)
                            {
                                //strAction = "<span class=\"delete\"><a onclick=\"javascript:return confirm('Are you sure ?!')\" href=\"?action=Delete&CatID=" + listView.CatId + "\">Xóa</a></span>";
                                strAction = "";
                                strWrite.Append("<td align=\"center\"><input type=\"checkbox\" class=\"checkbox\" name=\"cboCheck\" value=\"").Append(listView.CatId).Append("\" /></td>");
                            }
                            else
                            {
                                strAction = "";
                                strWrite.Append("<td align=\"center\"></td>");
                            }
                            strWrite.Append("<td onmouseover=\"javascript:Util.DisplayAction(").Append(listView.CatId).Append(");\" onmouseout=\"javascript:Util.HideAction(").Append(listView.CatId).Append(");\"><a class=\"lnkArticle\" href=\"?action=Edit&CatID=").Append(listView.CatId).Append("\" title=\"").Append(listView.Title).Append("\">+--- ").Append(listView.Title).Append("</a><div style=\"display:none;\" class=\"row-actions\" id=\"row-actions-").Append(listView.CatId).Append("\"><span class=\"edit\"><a href=\"?action=Edit&CatID=").Append(listView.CatId).Append("\">Sửa</a> | </span>").Append(strAction).Append("</div></td>");
                            strWrite.Append("<td>").Append(listView.Description).Append("</td>");
                            strWrite.Append("<td align=\"center\">").Append((listView.SiteId == 1 ? "Có" : "Không")).Append("</td>");
                            strWrite.Append("</tr>");
                            break;
                        case 3:
                            strWrite.Append(
                                "<span class=\"cboCatItem\"><label>&nbsp;&nbsp;&nbsp;<input type=\"checkbox\" name=\"cboCategory\" id=\"cboCategory")
                                .Append(listView.CatId).Append("\" value=\"").Append(listView.CatId).Append("|").Append(
                                    listView.SubCat).Append("|").Append(listView.SubCatx).Append("\" />").Append(
                                        listView.Title).Append("</label></span>");
                            break;
                        default:
                            if (type == 2 || type == 4 || type == 5)
                            {
                                if (listView.CatId != notIn)
                                {
                                    if (selectedId == Convert.ToString(listView.CatId))
                                    {
                                        strWrite.Append("<option selected=\"selected\" value=\"").Append(listView.CatId)
                                            .Append(",").Append(listView.SubCat).Append(",").Append(
                                                listView.SubCatx).Append("\">----").Append(listView.Title).
                                            Append("</option>");
                                    }
                                    else if (listView.CatId != 1)
                                    {
                                        strWrite.Append("<option value=\"").Append(listView.CatId).Append(",").Append(
                                            listView.SubCat).Append(",").Append(listView.SubCatx).Append
                                            ("\">----").Append(listView.Title).Append("</option>");
                                    }
                                }
                            }
                            break;
                    }

                    var reader3 = GetParentCat(listView.SubCat, listView.CatId);

                    foreach (var viewCat in reader3)
                    {
                        switch (type)
                        {
                            case 1:
                                //strWrite.Append(i % 2 == 0 ? "<tr style=\"background-color:#F9F9F9;\">" : "<tr>");
                                strWrite.Append("<tr>");

                                if (viewCat.CatId != 1)
                                {
                                    strAction = "";
                                    //strAction = "<span class=\"delete\"><a onclick=\"javascript:return confirm('Are you sure ?!')\" href=\"?action=Delete&CatID=" + viewCat.CatId + "\">Xóa</a></span>";
                                    strWrite.Append("<td align=\"center\"><input type=\"checkbox\" class=\"checkbox\" name=\"cboCheck\" value=\"").Append(viewCat.CatId).Append("\" /></td>");
                                }
                                else
                                {
                                    strAction = "";
                                    strWrite.Append("<td align=\"center\"></td>");
                                }
                                strWrite.Append("<td onmouseover=\"javascript:Util.DisplayAction(").Append(viewCat.CatId).Append(");\" onmouseout=\"javascript:Util.HideAction(").Append(viewCat.CatId).Append(");\"><a class=\"lnkArticle\" href=\"?action=Edit&CatID=").Append(viewCat.CatId).Append("\" title=\"").Append(viewCat.Title).Append("\">+------ ").Append(viewCat.Title).Append("</a><div style=\"display:none;\" class=\"row-actions\" id=\"row-actions-").Append(viewCat.CatId).Append("\"><span class=\"edit\"><a href=\"?action=Edit&CatID=").Append(viewCat.CatId).Append("\">Sửa</a> | </span>").Append(strAction).Append("</div></td>");
                                strWrite.Append("<td>").Append(viewCat.Description).Append("</td>");
                                strWrite.Append("<td align=\"center\">").Append((viewCat.SiteId == 1 ? "Có" : "Không")).Append("</td>");
                                strWrite.Append("</tr>");
                                break;
                            case 3:
                                strWrite.Append(
                                    "<span class=\"cboCatItem\"><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"checkbox\" name=\"cboCategory\" id=\"cboCategory")
                                    .Append(viewCat.CatId).Append("\" value=\"").Append(viewCat.CatId).Append("|").
                                    Append(viewCat.SubCat).Append("|").Append(viewCat.SubCatx).Append("\" />").Append(
                                        viewCat.Title).Append("</label></span>");
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            if (type == 1)
            {
                strWrite.Append("<tr class=\"header\">");
                strWrite.Append("<th align=\"center\"><input type=\"checkbox\" name=\"cboCheck\" class=\"check_all\" /></th>");
                strWrite.Append("<th>Tên danh mục</th>");
                strWrite.Append("<th>Mô tả</th>");
                strWrite.Append("<th align=\"center\">Posts</th>");
                strWrite.Append("</tr>");
                strWrite.Append("</table>");
            }
            else if (type == 2 | type == 4 | type == 5)
            {
                strWrite.Append("</select>");
            }
            else if (type == 3)
            {
                strWrite.Append("</div>");
                if (!string.IsNullOrEmpty(selectedId))
                {
                    strWrite.Append("<script language=\"javascript\" type=\"text/javascript\">");
                    foreach (var strCat in
                        Regex.Split(selectedId, ",").Where(strCat => !string.IsNullOrEmpty(strCat)))
                    {
                        strWrite.Append("gmobj(\"cboCategory").Append(strCat).Append("\").checked = true;");
                    }
                    strWrite.Append("</script>");
                }
            }

            return strWrite.ToString();
        }
    }
}